package GUIuse;

import GUIuse.mainuse.OrderManagementSystem;
import common.Customer;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class CustomerPanel extends JPanel {
    private OrderManagementSystem parent;
    private JTable customerTable;
    private DefaultTableModel tableModel;
    private JButton addButton, editButton, deleteButton, refreshButton;
    
    public CustomerPanel(OrderManagementSystem parent) {
        this.parent = parent;
        initialize();
    }
    
    private void initialize() {
        setLayout(new BorderLayout());
        
        // 创建表格模型和表格
        String[] columnNames = {"客户编号", "客户名称", "联系人", "联系电话", "地址", "邮箱", "状态"};
        tableModel = new DefaultTableModel(columnNames, 0);
        customerTable = new JTable(tableModel);
        customerTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(customerTable);
        add(scrollPane, BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        
        addButton = new JButton("添加客户");
        editButton = new JButton("修改客户");
        deleteButton = new JButton("删除客户");
        refreshButton = new JButton("刷新");
        
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(refreshButton);
        
        add(buttonPanel, BorderLayout.NORTH);
        
        // 添加按钮事件监听
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddCustomerDialog();
            }
        });
        
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showEditCustomerDialog();
            }
        });
        
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteSelectedCustomer();
            }
        });
        
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable();
            }
        });
        
        // 初始加载数据
        refreshTable();
    }
    
    // 刷新表格数据
    public void refreshTable() {
        tableModel.setRowCount(0); // 清空表格
        List<Customer> customers = parent.getCustomers();
        for (Customer customer : customers) {
            Object[] rowData = {
                customer.getId(),
                customer.getName(),
                customer.getContactPerson(),
                customer.getPhone(),
                customer.getAddress(),
                customer.getEmail(),
                customer.isActive() ? "有效" : "无效"
            };
            tableModel.addRow(rowData);
        }
    }
    
    // 显示添加客户对话框
    private void showAddCustomerDialog() {
        JDialog dialog = new JDialog((Frame) null, "添加客户", true);
        dialog.setSize(500, 400);
        dialog.setLocationRelativeTo(null);
        dialog.setLayout(new BorderLayout());
        
        JPanel panel = new JPanel(new GridLayout(8, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        // 创建输入字段
        JLabel idLabel = new JLabel("客户编号:");
        JTextField idField = new JTextField();
        
        JLabel nameLabel = new JLabel("客户名称:");
        JTextField nameField = new JTextField();
        
        JLabel contactPersonLabel = new JLabel("联系人:");
        JTextField contactPersonField = new JTextField();
        
        JLabel phoneLabel = new JLabel("联系电话:");
        JTextField phoneField = new JTextField();
        
        JLabel addressLabel = new JLabel("地址:");
        JTextField addressField = new JTextField();
        
        JLabel emailLabel = new JLabel("邮箱:");
        JTextField emailField = new JTextField();
        
        JLabel noteLabel = new JLabel("备注:");
        JTextField noteField = new JTextField();
        
        panel.add(idLabel);
        panel.add(idField);
        panel.add(nameLabel);
        panel.add(nameField);
        panel.add(contactPersonLabel);
        panel.add(contactPersonField);
        panel.add(phoneLabel);
        panel.add(phoneField);
        panel.add(addressLabel);
        panel.add(addressField);
        panel.add(emailLabel);
        panel.add(emailField);
        panel.add(noteLabel);
        panel.add(noteField);
        
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 保存按钮事件
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int id = Integer.parseInt(idField.getText());
                    String name = nameField.getText();
                    String contactPerson = contactPersonField.getText();
                    String phone = phoneField.getText();
                    String address = addressField.getText();
                    String email = emailField.getText();
                    String note = noteField.getText();
                    
                    if (name.isEmpty() || contactPerson.isEmpty() || phone.isEmpty()) {
                        JOptionPane.showMessageDialog(dialog, "客户名称、联系人、联系电话为必填项", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    
                    Customer customer = new Customer(id, name, contactPerson, phone, address, email);
                    customer.setNote(note);
                    
                    // 检查ID是否已存在
                    for (Customer c : parent.getCustomers()) {
                        if (c.getId() == id) {
                            JOptionPane.showMessageDialog(dialog, "客户编号已存在", "错误", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                    
                    parent.addCustomer(customer);
                    refreshTable();
                    dialog.dispose();
                    JOptionPane.showMessageDialog(parent, "客户添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(dialog, "客户编号必须为数字", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        
        // 取消按钮事件
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        
        dialog.setVisible(true);
    }
    
    // 显示修改客户对话框
    private void showEditCustomerDialog() {
        int selectedRow = customerTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要修改的客户", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        Customer customerToEdit = null;
        
        for (Customer customer : parent.getCustomers()) {
            if (customer.getId() == id) {
                customerToEdit = customer;
                break;
            }
        }
        
        if (customerToEdit == null) {
            JOptionPane.showMessageDialog(this, "未找到选中的客户", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        JDialog dialog = new JDialog((Frame) null, "修改客户", true);
        dialog.setSize(500, 400);
        dialog.setLocationRelativeTo(null);
        dialog.setLayout(new BorderLayout());
        
        JPanel panel = new JPanel(new GridLayout(8, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        // 创建输入字段并填充当前值
        JLabel idLabel = new JLabel("客户编号:");
        JTextField idField = new JTextField(String.valueOf(customerToEdit.getId()));
        idField.setEditable(false); // 客户编号不可修改
        
        JLabel nameLabel = new JLabel("客户名称:");
        JTextField nameField = new JTextField(customerToEdit.getName());
        
        JLabel contactPersonLabel = new JLabel("联系人:");
        JTextField contactPersonField = new JTextField(customerToEdit.getContactPerson());
        
        JLabel phoneLabel = new JLabel("联系电话:");
        JTextField phoneField = new JTextField(customerToEdit.getPhone());
        
        JLabel addressLabel = new JLabel("地址:");
        JTextField addressField = new JTextField(customerToEdit.getAddress());
        
        JLabel emailLabel = new JLabel("邮箱:");
        JTextField emailField = new JTextField(customerToEdit.getEmail());
        
        JLabel noteLabel = new JLabel("备注:");
        JTextField noteField = new JTextField(customerToEdit.getNote());
        
        JLabel statusLabel = new JLabel("状态:");
        JComboBox<String> statusComboBox = new JComboBox<>(new String[]{"有效", "无效"});
        statusComboBox.setSelectedItem(customerToEdit.isActive() ? "有效" : "无效");
        
        panel.add(idLabel);
        panel.add(idField);
        panel.add(nameLabel);
        panel.add(nameField);
        panel.add(contactPersonLabel);
        panel.add(contactPersonField);
        panel.add(phoneLabel);
        panel.add(phoneField);
        panel.add(addressLabel);
        panel.add(addressField);
        panel.add(emailLabel);
        panel.add(emailField);
        panel.add(noteLabel);
        panel.add(noteField);
        panel.add(statusLabel);
        panel.add(statusComboBox);
        
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 保存按钮事件
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String name = nameField.getText();
                    String contactPerson = contactPersonField.getText();
                    String phone = phoneField.getText();
                    String address = addressField.getText();
                    String email = emailField.getText();
                    String note = noteField.getText();
                    boolean active = statusComboBox.getSelectedItem().equals("有效");
                    
                    if (name.isEmpty() || contactPerson.isEmpty() || phone.isEmpty()) {
                        JOptionPane.showMessageDialog(dialog, "客户名称、联系人、联系电话为必填项", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    
                    Customer updatedCustomer = new Customer(id, name, contactPerson, phone, address, email);
                    updatedCustomer.setNote(note);
                    updatedCustomer.setActive(active);
                    
                    parent.updateCustomer(updatedCustomer);
                    refreshTable();
                    dialog.dispose();
                    JOptionPane.showMessageDialog(parent, "客户修改成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(dialog, "修改失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        
        // 取消按钮事件
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        
        dialog.setVisible(true);
    }
    
    // 删除选中的客户
    private void deleteSelectedCustomer() {
        int selectedRow = customerTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的客户", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        String name = (String) tableModel.getValueAt(selectedRow, 1);
        
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除客户" + name + "吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            parent.deleteCustomer(id);
            refreshTable();
            JOptionPane.showMessageDialog(this, "客户删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}